/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple.utils.data;

import java.io.*;

/**
 *
 * @author rehak
 *
 * Date : 16.2.2012 Time : 16:43:29
 */
public class StreamUtils {

    /**
     * Read whole input stream, does not close it
     *
     * @param in
     * @param bufferSize
     * @return
     * @throws java.io.IOException
     */
    public static byte[] readStream(InputStream in, int bufferSize) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] d = new byte[bufferSize];
        int read;
        while ((read = in.read(d)) > -1) {
            bos.write(d, 0, read);
        }
        return bos.toByteArray();
    }

    public static String readString(InputStream in, int bufferSize, boolean close, String encoding) throws IOException {
        byte[] b = readStream(in, bufferSize, close);
        String s = new String(b, encoding);
        return s;
    }
    
    public static byte[] readStream(InputStream in, int bufferSize, boolean close) throws IOException {
        byte[] data = readStream(in, bufferSize);
        if (close) {
            in.close();
        }
        return data;
    }

    public static void writeStreamToStream(InputStream in, int bufferSize, OutputStream out) throws IOException {
        byte[] d = new byte[bufferSize];
        int read;
        while ((read = in.read(d)) > -1) {
            out.write(d, 0, read);
        }
    }

    public static void writeToFile(File file, byte[] data, boolean append) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(file,append)) {
            fos.write(data);
            fos.flush();
        }
    }
    
    public static void writeToFile(File file, String string, boolean append) throws IOException {
        writeToFile(file, string.getBytes("UTF-8"), append);
    }
}
